package com.token.config;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.token.mapper.SysPermissionMapper;
import com.token.mapper.SysRoleMapper;
import com.token.mapper.SysUserRoleMapper;
import com.token.model.po.SysPermission;
import com.token.model.po.SysRole;
import com.token.model.po.SysUserRole;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 该类配合接口权限、角色认证使用
 *
 * @auther: henriy
 * @Date: 2023/10/25
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysPermissionMapper sysPermissionMapper;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        LambdaQueryWrapper<SysPermission> sysPermissionQueryWrapper = Wrappers.lambdaQuery();
        sysPermissionQueryWrapper.eq(SysPermission::getUserId, loginId.toString());
        return sysPermissionMapper.selectList(sysPermissionQueryWrapper)
                .stream()
                .map(SysPermission::getPermCode)
                .collect(Collectors.toList());
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        LambdaQueryWrapper<SysUserRole> userRoleQueryWrapper = Wrappers.lambdaQuery();
        userRoleQueryWrapper.eq(SysUserRole::getUserId, loginId.toString());
        List<Long> roleIdList = sysUserRoleMapper.selectList(userRoleQueryWrapper)
                .stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());

        LambdaQueryWrapper<SysRole> roleQueryWrapper = Wrappers.lambdaQuery();
        roleQueryWrapper.in(SysRole::getId, roleIdList);
        return sysRoleMapper.selectList(roleQueryWrapper)
                .stream()
                .map(SysRole::getRoleCode)
                .collect(Collectors.toList());
    }

}
